#!/usr/bin/env python3
import os
import subprocess
import sys
import threading
import shutil

def thread(docker, num, delay, file):
    print("delay: start", delay)
 
    command="docker exec -it  --privileged   %s sysbench  --db-driver=mysql \
    --mysql-host=localhost --mysql-port=3306 --mysql-user=root  --mysql-db=testdb128  --tables=150 \
    --events=0 --time=%d  --threads=%d --percentile=95 --report-interval=1 oltp_read_only run >> %s; \
    " % (docker, int(delay), num, file)

    #os.system(command)
    result = subprocess.run(command, shell=True, text=True, capture_output=True)

    print("delay: end", delay)

def do_the_test(num, delay, benchmakr_name, sysctl_value):
    threads = []
    docker = ["parameter_test_001", "parameter_test_002", "parameter_test_003"]

    src_dir = "./tmp"
    dest_dir = "./history"

    isExists=os.path.exists(src_dir)
    if not isExists:
        os.makedirs(src_dir)
    isExists=os.path.exists(dest_dir)
    if not isExists:
        os.makedirs(dest_dir)

    for i in range(3):
        benchmark_file = "./tmp/%d.%s" % ((i + 1), benchmakr_name)
        with open(benchmark_file, 'w') as file:
            print("\nfile:"+ sysctl_value + "\n", file=file, end=' ', flush=True)
        t = threading.Thread(target=thread, args=(docker[i], (1 << i)* 8, delay, benchmark_file))
        threads.append(t)
        t.start()

    # 等待所有线程执行完毕
    for t in threads:
        t.join()

    for i in range(3):
        src_file = "./tmp/%d.%s" % ((i + 1), benchmakr_name)
        dest_file = "./history/%d.%s" % ((i + 1), benchmakr_name)
        shutil.move(src_file, dest_file)

    print("All threads are finished.")

